package com.rongshu.view.mediaPlayer.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.DateUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetView;
import com.rongshu.view.mediaPlayer.adapter.AudiobookListAdapter;
import com.rongshu.view.mediaPlayer.bean.AudiobookDetailsResponse;
import com.rongshu.view.mediaPlayer.bean.AudiobookListResponse;
import com.rongshu.view.mediaPlayer.bean.PlayEvent;
import com.rongshu.view.mediaPlayer.manager.PlayerManager;
import com.rongshu.view.mediaPlayer.presenter.AudiobookListPresenter;
import com.widget.datapicker.builder.TimePickerBuilder;
import com.widget.datapicker.listener.OnTimeSelectListener;
import com.widget.datapicker.view.TimePickerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengweis on 2019/4/25.
 * description：
 */
public class AudiobookListActivity extends BaseActivity<AudiobookListPresenter> implements INetView {
    @BindView(R.id.head_middle)
    TextView headMiddle;
    @BindView(R.id.media_list)
    RecyclerView mediaList;
    @BindView(R.id.current_date)
    TextView currentDateTv;
    private AudiobookListAdapter adapter;
    private TimePickerView timePickerView;
    private List<AudiobookListResponse.ResponseBean> beanList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_media_list;
    }

    @Override
    protected void initView() {
        headMiddle.setText("声音");
        beanList = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        adapter = new AudiobookListAdapter(this, beanList);
        mediaList.setLayoutManager(manager);
        mediaList.setAdapter(adapter);
        initTimePicker();
        mediaList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int position = layoutManager.findFirstVisibleItemPosition();
                updateCurrentSelectDate(position);
            }
        });
    }

    private void initTimePicker() {
        //正确设置方式 原因：注意事项有说明
        Calendar startDate = Calendar.getInstance();
        //有声文字日期从五月份开始
        startDate.set(2019, 5, 0);
        Date curDate = new Date(System.currentTimeMillis());
        Calendar endDate = Calendar.getInstance();
        endDate.setTime(curDate);
        if (startDate.getTimeInMillis() > endDate.getTimeInMillis()) {
            endDate = startDate;
        }
        timePickerView = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                boolean contain = linkageSelectedDate(date);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                currentDateTv.setText(calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月");
                if (!contain) {
                    toast("当前日期没有可播放音频");
                }
            }
        }).setType(new boolean[]{true, true, false, false, false, false})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .setSubmitText(getString(R.string.complete))
                .setSubmitColor(ContextCompat.getColor(this, R.color.color_3cc051))
                .setCancelColor(ContextCompat.getColor(this, R.color.color_3cc051))
                .setTitleBgColor(ContextCompat.getColor(this, R.color.white_loading_color))
                .setBgColor(ContextCompat.getColor(this, R.color.white_loading_color))
                .setTextColorCenter(ContextCompat.getColor(this, R.color.color_4a4a4a))
                .setTextColorOut(ContextCompat.getColor(this, R.color.color_666666))
                .setSubCalSize(14)
                .setRangDate(startDate, endDate)
                .build();
    }

    @Override
    protected void initData() {
        setPresenter(new AudiobookListPresenter(this), this);
        presenter.requestAudiobookList();
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (PlayerManager.getPlayer().isPlaying()) {
            showBarChart();
        } else {
            hideBarChart();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.head_left, R.id.top_option})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_left:
                finish();
                break;
            case R.id.top_option:
                if (timePickerView != null) {
                    timePickerView.show();
                }
                break;
        }
    }

    //监听行为控制音浪效果
    @Subscribe
    public void onEvent(PlayEvent playEvent) {
        if (beanList == null || adapter == null) {
            return;
        }
        switch (playEvent.getAction()) {
            case PLAY:
                showBarChart();
                break;
            case PAUST:
            case STOP:
            case OVER:
                hideBarChart();
                break;

        }
    }

    /**
     * 正在播放的音频，该item显示音浪效果
     */
    private void showBarChart() {
        AudiobookDetailsResponse.ResponseBean song = PlayerManager.getPlayer().getNowPlaying();
        if (beanList != null && song != null) {
            for (AudiobookListResponse.ResponseBean event : beanList) {
                if (event.getId() == song.getId()) {
                    event.setPlayState(true);
                } else {
                    event.setPlayState(false);
                }
            }
            adapter.notifyDataSetChanged();
        }
    }

    private void hideBarChart() {
        if (beanList != null) {
            for (AudiobookListResponse.ResponseBean bean : beanList) {
                bean.setPlayState(false);
            }
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void success(Object object, int tag) {
        AudiobookListResponse response = (AudiobookListResponse) object;
        if (response != null) {
            beanList.addAll(response.getResponse());
            if (PlayerManager.getPlayer().isPlaying()) {
                showBarChart();
            } else {
                hideBarChart();
            }
        }
        if (beanList.size() > 0) {
            updateCurrentSelectDate(0);
        }
        View v = LayoutInflater.from(this).inflate(R.layout.layout_recyclerview_foot, mediaList, false);
        adapter.setFooterView(v);
    }

    @Override
    public void faild(Object object, int tag) {

    }

    /**
     * 更新当前显示日期
     *
     * @param position
     */
    private void updateCurrentSelectDate(int position) {
        String createDateTime = beanList.get(position).getDailyDate();
        Date date = DateUtils.parseDate(DateUtils.YYYY_MM_DD_HH_MM_SS, createDateTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        timePickerView.setDate(calendar);
        currentDateTv.setText(calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月");
    }

    /**
     * 选择日期，列表联动
     *
     * @return 列表是否包含有该日期
     */
    private boolean linkageSelectedDate(Date date) {
        boolean contain = false;
        if (beanList != null) {
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMM");
            for (int position = 0; position < beanList.size(); position++) {
                AudiobookListResponse.ResponseBean bean = beanList.get(position);
                String createDateTime = bean.getDailyDate();
                Date positionDate = DateUtils.parseDate(DateUtils.YYYY_MM_DD_HH_MM_SS, createDateTime);
                if (TextUtils.equals(fmt.format(date), fmt.format(positionDate))) {
                    mediaList.scrollToPosition(position);
                    LinearLayoutManager mLayoutManager = (LinearLayoutManager) mediaList.getLayoutManager();
                    mLayoutManager.scrollToPositionWithOffset(position, 0);
                    contain = true;
                    break;
                } else {
                    contain = false;
                }
            }
        }
        return contain;
    }
}
